package com.devicemantra.coordinate.dataobjects;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.JDOException;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.devicemantra.coordinate.ds.tests.PMF;
import com.devicemantra.coordinate.exceptions.dataobjects.CDatabaseException;
import com.devicemantra.coordinate.exceptions.operations.CStateAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CStateDoesNotExistsException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/** TODO - Most of the *Factory classes are written very badly 
 * put some thought into optimizing for performance */

public  class CContactsFactory 
{
	public static List<CContact> getContactsForLocation(String pLocationId)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<CContact> lContactList = null;
		pm.getFetchPlan().setMaxFetchDepth(3);
		javax.jdo.Query query = pm.newQuery(CContact.class, "mLocationId == pLocationId");
		 /*query.setFilter("mDestinationFrameId == lCFrameId");
		 query.setFilter("mIsRead == lIsTrue"); */
		 query.declareParameters("String pLocationId");
		 lContactList = (List<CContact>) query.execute(pLocationId);
		 lContactList = (List<CContact>)pm.detachCopyAll(lContactList);
		 //pm.retrieveAll(lCFrameList);
		 System.out.println("Number of contacts found  for " + pLocationId + " is "  +  lContactList.size());
		 pm.close();
		 return lContactList;
		
	}
		public static List<CContact> getContactsForLocations(List<String> pLocationList) {
			List<CContact> lMainContactList =  new ArrayList<CContact>();
			for(int lCounter = 0; lCounter < pLocationList.size(); lCounter++) {
				List<CContact> lCurrentList = new ArrayList<CContact>(10);
				String lLocationId = pLocationList.get(lCounter);
				lCurrentList = getContactsForLocation(lLocationId);
				if( (lCurrentList != null) && (lCurrentList.size() > 0)) {
					lMainContactList.addAll(lCurrentList);
					System.out.println("Current contacts retreived from [" + lLocationId + "] is" +  lMainContactList.size());
					System.out.println("Total contacts  is [NOW]" + lMainContactList.size());	
				}
			}
			System.out.println("Total contacts retreived is " + lMainContactList.size());	
			return lMainContactList;
		}
		
}
